package inc.gome.dynamic.datasource.logread;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;



/**
 * @author 苏继宙
 * @Date   2021-12-01
 * @Desc   缓存区定义，优先将内容加载到内存中（注意此类的使用 读取数据过量容易OOM）
 */
public class ByteBuffer extends OutputStream {
    private byte[] buf = new byte[8192];

    /**
     * Size of the data.  定义读取数据
     */
    private int size = 0;


    //加锁写
    public synchronized void write(byte b[], int off, int len) throws IOException {
        ensureCapacity(len);
        System.arraycopy(b,off,buf,size,len);
        size+=len;
    }


    public synchronized void write(int b) throws IOException {
        ensureCapacity(1);
        buf[size++] = (byte)b;
    }

    public synchronized long length() {
        return size;
    }

    private void ensureCapacity(int len) {
        if(buf.length-size>len)
            return;

        byte[] n = new byte[Math.max(buf.length*2, size+len)];
        System.arraycopy(buf,0,n,0,size);
        this.buf = n;
    }

    public synchronized String toString() {
        return new String(buf,0,size);
    }


    /**
     * @param os   输出流
     * @throws IOException
     */
    public synchronized void writeTo(OutputStream os) throws IOException {
        os.write(buf,0,size);
    }


    /**
     *  获取输入流
     * @return
     */
    public InputStream newInputStream() {
        return new InputStream() {
            private int pos = 0;
            public int read() throws IOException {
                synchronized(ByteBuffer.this) {
                    if(pos>=size)   return -1;
                    return buf[pos++];
                }
            }

            public int read(byte b[], int off, int len) throws IOException {
                synchronized(ByteBuffer.this) {
                    if(size==pos)
                        return -1;

                    int sz = Math.min(len,size-pos);
                    System.arraycopy(buf,pos,b,off,sz);
                    pos+=sz;
                    return sz;
                }
            }
            public int available() throws IOException {
                synchronized(ByteBuffer.this) {
                    return size-pos;
                }
            }
            public long skip(long n) throws IOException {
                synchronized(ByteBuffer.this) {
                    int diff = (int) Math.min(n,size-pos);
                    pos+=diff;
                    return diff;
                }
            }
        };
    }
}